# 超时
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        n = len(nums)
        min_z = float("inf")
        ans = [None] * 3
        # 求绝对值
        def abs(x):
            return x if x >= 0 else -x
        # 暴力解法
        for i in range(n):
            for j in range(i + 1, n):
                for z in range(j + 1, n):
                    res = abs(target - (nums[i] + nums[j] + nums[z]))
                    if res < min_z:
                        min_z = min(res, min_z)
                        # 有更接近target的值时更新答案数组
                        ans[0], ans[1], ans[2] = nums[i], nums[j], nums[z]
        return ans[0] + ans[1] + ans[2]

# 方法二 排序+双指针
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums = sorted(nums)
        n = len(nums)
        ans = float("inf")
        # 求绝对值
        def abs(x):
            return x if x >= 0 else -x
        for i in range(n):
            start, end = i + 1, n - 1
            while start < end:
                total = nums[i] + nums[start] + nums[end]
                if abs(target -total) < abs(target - ans):
                    ans = total
                if total == target:
                    return target
                elif total > target:
                    end -= 1
                else:
                    start += 1
        return ans
